package com.deyuanyun.pic.settings.controller;

import com.deyuanyun.pic.common.util.DateUtil;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;

import java.beans.PropertyEditorSupport;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Date;

/**
 * Created by linwei on 2015/8/4.
 */
public abstract class BaseController {

    /**
     * 日志
     */
    protected Logger logger = LogManager.getLogger(this.getClass());

    /**
     * 得到日志
     *
     * @return
     */
    public Logger getLogger() {
        return logger;
    }

    /**
     * 路径编码器
     * @param value java.long.String 传入值
     * @return java.long.String 返回编码后的字符串
     */
    protected String urlEncoder(String value) {
        try {
            return URLEncoder.encode(value, "utf-8");
        } catch (UnsupportedEncodingException e) {
            return value;
        }
    }

    /**
     * 路径解码器
     *
     * @param value java.long.String 传入值
     * @return java.long.String 返回解码后的字符串
     */
    protected String urlDecoder(String value) {
        try {
            return URLDecoder.decode(value, "utf-8");
        } catch (UnsupportedEncodingException e) {
            return value;
        }
    }

    /**初始化时设置一些参数的转换*/
    @InitBinder
    protected void initBinder(WebDataBinder binder) {
        /*binder.registerCustomEditor(Date.class, new CustomDateEditor(
                new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"), true));*/
        binder.registerCustomEditor(Date.class, new DateEditor());
        //binder.registerCustomEditor(int.class,new LongEditor());
    }

}

class DateEditor extends PropertyEditorSupport {
    static Logger logger = Logger.getLogger(DateEditor.class);
    @Override
    public void setAsText(String text) throws IllegalArgumentException {

        if ( !StringUtils.hasText(text)) {
            setValue(null);
        }
        else {
            try {
                if (text.contains("-") && text.contains(":")){
                    setValue(DateUtil.str2DateTime(text));
                }else if (text.contains("-") && !text.contains(":")){
                    setValue(DateUtil.str2Date(text));
                }

            } catch (Exception e) {
                logger.error("日期转换出错！"+text+"||",e);
            }
        }
    }
    /**
     * Format the Date as String, using the specified DateFormat.
     */
    @Override
    public String getAsText() {
        return getValue().toString();
    }
}